//
//  YRHomeTableViewController.swift
//  YR 微博
//
//  Created by cyr on 15/10/8.
//  Copyright © 2015年 cyr. All rights reserved.
//

import UIKit

class YRHomeTableViewController: YRBaseViewController {

    /**
    微博数据数组
    */
    var statuses: [YRStatus]? {
        didSet {
            tableView.reloadData()
        }
    }
    
    // MARK: - 数据源方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return statuses?.count ?? 0
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let status = statuses![indexPath.row]
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status), forIndexPath: indexPath) as! YRStatusCell
        
        // 判断 indexPath 的数值
        if indexPath.row == statuses!.count - 1 {
            pullupRefreshFlag = true
            loadData()
        }
        
        cell.status = statuses![indexPath.row]
        
        return cell
    }
    
   
    // MARK: - 代理方法
    /**
    返回行高
    */
    override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        let status = statuses![indexPath.row]
        
        if let h = status.rowHeight {
            return h
        }
        
        let cell = tableView.dequeueReusableCellWithIdentifier(StatusCellIdentifier.cellId(status)) as? YRStatusCell
        
        status.rowHeight = cell!.rowHeight(status)

        return status.rowHeight!
                
    }
   
    override func viewDidLoad() {
        super.viewDidLoad()
        
        if !YRUserAccount.userLogon {
        visitorView?.setupViewInfo(true, imageName: "visitordiscover_feed_image_smallicon", message: "关注一些人，回这里看看有什么惊喜")
                return
        }
        
        
  
        prepareTableView()
        
        loadData()
    }
    
    /**
    准备表格视图
    */
    private func prepareTableView() {
        
        // 注册原型 cell
        tableView.registerClass(YRStatusNormalCell.self, forCellReuseIdentifier: StatusCellIdentifier.NormalCell.rawValue)
        tableView.registerClass(YRStatusForwardCell.self, forCellReuseIdentifier: StatusCellIdentifier.ForwardCell.rawValue)
        
        //        tableView.estimatedRowHeight = 200
        //
        //        tableView.rowHeight = UITableViewAutomaticDimension
        
        tableView.estimatedRowHeight = 300
        
        // 取消分割线
        tableView.separatorStyle = UITableViewCellSeparatorStyle.None
        
        refreshControl = YRRefreshControl()
        
        refreshControl?.addTarget(self, action: "loadData", forControlEvents: UIControlEvents.ValueChanged)
    }
    
    
    
    /**
    *  加载数据
    */
    
    /**
    上啦刷新的标记
    */
    private var pullupRefreshFlag = false
    func loadData() {
        refreshControl?.beginRefreshing()
        
        var since_id = statuses?.first?.id ?? 0
        var max_id = 0
        if pullupRefreshFlag {
            since_id = 0
            max_id = statuses?.last?.id ?? 0
        }
        
        
       YRStatus.loadStatus(since_id, max_id: max_id) {(dataList, error) -> () in
        
        self.refreshControl?.endRefreshing()
        
        if error != nil {
            print(error)
            return
        }
        
        let count = dataList?.count ?? 0
        if since_id > 0 {
            self.showPulldownTip(count)
        }
        
        print("刷新到\( count)条数据")
        
        if count == 0 {
            return
        }
        
        if since_id > 0 {
            self.statuses = dataList! + self.statuses!
        } else if max_id > 0 {
            self.statuses! += dataList!
            self.pullupRefreshFlag = false
        } else {
            self.statuses = dataList
        }
        }
    }

    /**
    *  显示下来刷新的数据条数
    */
    private func showPulldownTip(count: Int) {
     
        if tipLabel.layer.animationForKey("position") != nil {
            print("动画正在执行中")
            return
        }
        
        tipLabel.text = (count == 0) ? "暂时没有新的微博" : "刷新到\(count)条微博"
     
        let rect = tipLabel.frame
        // 设置动画
        UIView.animateWithDuration(1.0, animations: { () -> Void in
        
            // 设置自动翻转
            UIView.setAnimationRepeatAutoreverses(true)
            // 移动标签的位置
            self.tipLabel.frame = CGRectOffset(rect, 0, 3 * rect.height)
            
            }) { (_) -> Void in
                
                //self.tipLabel.removeFromSuperview()
                self.tipLabel.frame = rect
                
        }
        
    }
    
    // MARK: -懒加载
    private lazy var tipLabel: UILabel = {
        // 定义标签
        let h: CGFloat = 44
        let label = UILabel(frame: CGRect(x: 0, y: -2 * h, width: self.view.bounds.width, height:h))
        label.backgroundColor = UIColor.orangeColor()
       
        label.textColor = UIColor.whiteColor()
        label.textAlignment = NSTextAlignment.Center
        
        // 添加到 navbar上
        self.navigationController?.navigationBar.insertSubview(label, atIndex: 0)
        
        return label
    }()
}
